import { message } from '@/components/XtxUI'
// 非vue组件，导入router路由实例，useRouter只能在setup中使用
import router from '@/router'
import type { OrderListInfo, Profile, UserAddresses } from '@/types'
import { http } from '@/utils/request'
import { defineStore, storeToRefs } from 'pinia'
import { computed, ref } from 'vue'
import { useCartStore } from '..'

export const useMemberStore = defineStore(
  'member',
  () => {
    const profile = ref<Profile>()
    const userAddressesList = ref<UserAddresses[]>([])
    const isLogin = computed(() => Boolean(profile.value?.token))

    // 登录成功跳转页面
    const loginSuccess = () => {
      const cartStore = useCartStore()
      const { cartList } = storeToRefs(cartStore)
      if (cartList.value.length > 0) {
        // 本地是否有购物车记录，有则合并本地购物车
        cartStore.mergeLocalCart()
      }
      message({ type: 'success', text: '登录成功' })
      /*
        在非.vue组件中useRoute()返回undefined，没法获取当前路由信息
        通过router路由实例的currentRoute属性获取当前路由信息
      */
      const { redirect = '/' } = router.currentRoute.value.query
      /*
        ?target=/goods/4026198&target=123
        target拿到的是数组，不要做任何兼容，因为没办法解决的，谁写bug让谁去修
      */
      // 重定向到指定地址，没有则跳转首页
      router.push(redirect as string)
    }

    // 用户名密码登录
    const accountLogin = async (data: { account: string; password: string }) => {
      const res = await http<Profile>('POST', '/login', data)
      profile.value = res.data.result
      loginSuccess()
    }

    // 退出登录
    const logout = () => {
      profile.value = {} as Profile
      message({ type: 'success', text: '退出成功' })
      // 清空购物车
      const cartStore = useCartStore()
      cartStore.clearCart()
      // 返回登录页
      router.push('/login')
    }

    // QQ第三方登录-账号手机号绑定
    const loginSocialBind = async (data: { unionId: string; mobile: string; code: string }) => {
      const res = await http<Profile>('POST', '/login/social/bind', data)
      profile.value = res.data.result
      loginSuccess()
    }

    // QQ第三方登录-获取手机号绑定的验证码
    const sentBindCode = async (mobile: string) => {
      await http('GET', '/login/social/code', { mobile })
    }

    // QQ第三方登录-已绑定手机号可直接登录
    const loginQQUnionId = async (data: { unionId: string; source: number }) => {
      const res = await http<Profile>('POST', '/login/social', data)
      profile.value = res.data.result
      loginSuccess()
    }

    // 新增收货地址信息
    const addUserAddress = async (data: object) => {
      await http('POST', '/member/address', data)
      message({ type: 'success', text: '新增地址成功' })
      // 获取最新收货地址信息
      getUserAddress()
    }

    // 获取收货地址信息
    const getUserAddress = async () => {
      const res = await http<UserAddresses[]>('GET', '/member/address')
      userAddressesList.value = res.data.result
    }

    // 获取订单列表信息
    const getOrderListInfo = async (query: {
      page: number
      pageSize: number
      orderState?: number
    }) => {
      const res = await http<OrderListInfo>('GET', '/member/order', query)
      return res.data.result
    }

    return {
      profile,
      isLogin,
      userAddressesList,
      accountLogin,
      logout,
      loginSocialBind,
      sentBindCode,
      loginQQUnionId,
      addUserAddress,
      getUserAddress,
      getOrderListInfo
    }
  },
  {
    persist: {
      key: 'rabbit-mall-member'
    }
  }
)
